<?php
/**
 * Created by PhpStorm.
 * User: Chris
 * Date: 14-3-23
 * Time: 下午5:55
 */
class Controller_Mobile_Base extends Controller_Template
{
    public $template = "template_mobile";

    protected function response_json($data){
        $body = \Format::forge($data)->to_json();

        $response = new Response($body, 200);
        $response->set_header('Content-Type', 'application/json');
        return $response;
    }



    public function before(){

        parent::before();
    }



    protected function get_session(){
        return Session::instance();
    }


    protected function get_uid($throwIfNull=false, $logon_uri=null){
        $uid = Session::get(SESSION_USER_ID);
        $username = Session::get(SESSION_USER_NAME);
        if ($uid==null || $username==null){
            if ($throwIfNull){
                throw new UserLoginRequireException($logon_uri);
            }
        }
        return $uid;



    }


    public static function forgePagination($uri, $size=10){
        return Pagination::forge('aitang_pagination', array(
            'pagination_url' => Uri::base() . $uri,
            'per_page' => $size,
            //            'uri_segment' => 3,
            // or if you prefer pagination by query string
            'uri_segment' => 'offset',
        ));
    }



    protected function user_login($user_id, $username){
        $login_hash = $this->create_login_hash($user_id);
        Session::set(SESSION_USER_ID, $user_id);
        Session::set(SESSION_USER_NAME, $username);
        Session::instance()->rotate();
    }


    protected function handle_user_login($user){
        $this->user_login($user->id, $user->name);
    }


    protected  function create_login_hash($user_id){
        $last_login = time();
        $salt = "zx2015";
        $login_hash = sha1($salt.  $user_id .$last_login);
        return $login_hash;
    }


}